package com.springcloud.eshop.datasync.rabbitmq.strategy;

import com.alibaba.fastjson.JSON;
import com.springcloud.eshop.datasync.enums.DataTypeEnum;
import com.springcloud.eshop.datasync.enums.EventTypeEnum;
import com.springcloud.eshop.datasync.rabbitmq.factory.DataChangeHandlerFactory;
import com.springcloud.eshop.datasync.service.EshopProductService;
import com.springcloud.eshop.entity.Brand;
import com.springcloud.eshop.message.AggrDataChangeMessage;
import com.springcloud.eshop.message.DataChangeMessage;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

/**
 * @Desc:
 * @Date: 2020-07-02
 * @Version:v1.0
 */
@Service
public class BrandDataChangeStrategy extends BaseDataChangeHandler implements InitializingBean {

    @Autowired
    private EshopProductService eshopProductService;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean handler(DataChangeMessage dataChangeMessage) {
        String eventType = dataChangeMessage.getEventType();
        boolean addOrUpdate = EventTypeEnum.isAddOrUpdate(eventType);
        if (addOrUpdate) {
            Brand brand = eshopProductService.selectOneBrand(dataChangeMessage.getId());
            jedisPool.getResource().set(getRedisKey(dataChangeMessage.getId()), JSON.toJSONString(brand));
        } else if (EventTypeEnum.DELETE.getType().equals(eventType)) {
            jedisPool.getResource().del(getRedisKey(dataChangeMessage.getId()));
        }
        addMessage(new AggrDataChangeMessage("brand", dataChangeMessage.getId()));
        return true;
    }

    @Override
    public String getRedisKey(long id) {
        return "brand_detail_" + id;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        DataChangeHandlerFactory.register(DataTypeEnum.BRAND.getType(), this);
    }
}
